/*
 *      system.cpp
 *
 *      Copyright 2009 AzureSky <AzureSky.fedora@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

#include "system.h"

sys_info::sys_info()
{
	uname(&name);
}

sys_info::~sys_info()
{
}

std::string sys_info::c_popen(std::string arg)
{
	char buf[512];
	FILE* fd;

	fd = popen(arg.c_str(),"r");

	fgets(buf,sizeof(buf),fd);
	pclose(fd);

	std::string temp_buf(buf);
	return std::string(temp_buf.begin(),temp_buf.end()-1);
}

std::string sys_info::get_dist_name()
{
	std::string dist_name = c_popen("cat /etc/issue.net | head -1");
	size_t found;
	found = dist_name.find('=');

	if(found != std::string::npos){
		std::string temp(dist_name,dist_name.find('=')+1,dist_name.length());
		dist_name = temp;
	}

	return (dist_name.empty()?"unknown":dist_name);
}

std::string sys_info::get_host_name()
{
	return name.nodename;
}

std::string sys_info::get_hard_platform()
{
	return name.machine;
}

std::string sys_info::get_kernel_release()
{
	return name.release;
}

std::string sys_info::get_kernel_version()
{
	return name.version;
}

std::string sys_info::get_sys_name()
{
	return name.sysname;
}

std::string sys_info::get_total_memory()
{
	std::string total_memory = c_popen("cat /proc/meminfo | grep 'MemTotal'");

	std::istringstream mem_num (total_memory.c_str());

	std::string mem_unit;
	double mem_size;

	mem_num >> mem_unit;
	mem_num >> mem_size;
	mem_num >> mem_unit;

	if (mem_size >= 1024.0){
		mem_size /= 1024.0;
		mem_unit = "Mb";

		if(mem_size >= 1024.0){
			mem_size /= 1024.0;
			mem_unit = "Gb";
		}
	}

	char mem_buf[20];
	memset(mem_buf,0,sizeof(mem_buf));
	sprintf(mem_buf,"%0.1f",mem_size);

	std::ostringstream out;
	out << mem_buf;
	out << ' ';
	out << mem_unit;

	return out.str();
}

std::string sys_info::get_cpu()
{
	std::string temp = c_popen("cat /proc/cpuinfo | grep 'model name'");
	std::string cpu_info(temp,temp.find(':')+2,temp.length());

	return cpu_info;
}
